package com.example.service.impl;

import com.example.context.BaseContext;
import com.example.dto.GoodsSalesDTO;
import com.example.entity.Orders;
import com.example.mapper.CustomerVipDao;
import com.example.mapper.OrdersDao;
import com.example.mapper.OrdersEmployeeDao;
import com.example.service.ReporterService;
import com.example.service.WorkspaceService;
import com.example.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * 1. @ClassDescription:
 * 2. @author: Z
 * 3. @date: 2024年05月18日 18:28
 */
@Service("reporterService")
@Slf4j
public class ReporterServiceImpl implements ReporterService {

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private OrdersEmployeeDao ordersEmployeeDao;

    @Autowired
    private CustomerVipDao customerVipDao;

    @Autowired
    private WorkspaceService workspaceService;

    private List<LocalDate> splitDate(LocalDate begin, LocalDate end){
        List<LocalDate> dates = new ArrayList<>();

        dates.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dates.add(begin);
        }
        return dates;
    }


    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = splitDate(begin,end);

        List<Double> turnoverList = new ArrayList<>();
        for(LocalDate date:dates){
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            map.put("storeId", BaseContext.getCurrentId2());
            Double t1 = ordersDao.sumByMap(map);
            Double t2 = ordersEmployeeDao.sumByMap(map);
            Double turnover = (t1 == null ? 0.0:t1) + (t2 == null ? 0.0:t1); ;
            turnover = turnover == null ? 0.0:turnover;
            turnoverList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = splitDate(begin,end);
        //每天新增用户量
        List<Integer> newUserList = new ArrayList<>();
        //每天用户总量
        List<Integer> totalUserList = new ArrayList<>();

        for(LocalDate date:dates){
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("end",endTime);
            int totalUser = customerVipDao.countByMap(map);
            map.put("begin",beginTime);
            int newUser = customerVipDao.countByMap(map);
            totalUserList.add(totalUser);
            newUserList.add(newUser);

        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = splitDate(begin, end);
        List<Integer> ordersList = new ArrayList<>();
        List<Integer> completedOrderList = new ArrayList<>();

        Integer allNum = 0;
        Integer allCompletedNum = 0;
        for(LocalDate date:dates){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("storeId",BaseContext.getCurrentId2());
            int ordersNum = ordersDao.countByMap(map) + ordersEmployeeDao.countByMap(map);
            map.put("status",Orders.COMPLETED);
            int completedOrderNum = ordersDao.countByMap(map) + ordersEmployeeDao.countByMap(map);
            allNum = allNum + ordersNum;
            allCompletedNum = allCompletedNum + completedOrderNum;
            ordersList.add(ordersNum);
            completedOrderList.add(completedOrderNum);
        }
        Double orderRate = 0.0;
        if(allNum!=0){
            orderRate = allCompletedNum.doubleValue() /allNum;
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dates,","))
                .orderCompletionRate(orderRate)
                .orderCountList(StringUtils.join(ordersList,","))
                .totalOrderCount(allNum)
                .validOrderCount(allCompletedNum)
                .validOrderCountList(StringUtils.join(completedOrderList,","))
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Long storeId = BaseContext.getCurrentId2();
        List<GoodsSalesDTO> goodsSalesDTOS = ordersDao.getSalesTop10(beginTime,endTime,storeId);
        List<GoodsSalesDTO> goodsSalesDTOS2 = ordersEmployeeDao.getSalesTop10(beginTime,endTime,storeId);
        log.info("ordersDao,{}",goodsSalesDTOS);
        log.info("ordersEmployeeDao,{}",goodsSalesDTOS2);
        //将两个list合并
        List<GoodsSalesDTO> newList = new ArrayList<>();
        goodsSalesDTOS2.addAll(goodsSalesDTOS);
        if(goodsSalesDTOS2.size()>0){
            newList.add(goodsSalesDTOS2.remove(0));
            int flag;
            for(GoodsSalesDTO goodsSales:goodsSalesDTOS2){
                flag = 0;
                for(GoodsSalesDTO goodsSales2:newList){
                    if(goodsSales2.getName() == goodsSales.getName()){
                        goodsSales2.setNumber(goodsSales.getNumber()+goodsSales2.getNumber());
                        flag = 1;
                        break;
                    }
                }
                if(flag == 0){
                    newList.add(goodsSales);
                }
            }
        }

        if(newList.size() > 10){
            newList = newList.subList(0,10);
        }

        newList.sort(new Comparator<GoodsSalesDTO>() {
            @Override
            public int compare(GoodsSalesDTO o1, GoodsSalesDTO o2) {
                return o2.getNumber() - o1.getNumber();
            }
        });

        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        if(newList!=null && newList.size()>0)
            for(GoodsSalesDTO goodsSalesDTO:newList){
                numberList.add(goodsSalesDTO.getNumber());
                nameList.add(goodsSalesDTO.getName());
            }

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
//查询数据库获取营业额数据,查询近三十天的数据
        LocalDate beginTime = LocalDate.now().minusDays(30);
        LocalDate endTime = LocalDate.now().minusDays(1);

        //查询数据库
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginTime,LocalTime.MIN), LocalDateTime.of(endTime,LocalTime.MAX));

        //通过poi将数据写入excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个excel
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取sheet页
            XSSFSheet sheet = excel.getSheetAt(0);
            //数据填充时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+beginTime+"至"+endTime);
            //获得第四行
            XSSFRow row4 = sheet.getRow(3);
            row4.getCell(2).setCellValue(businessData.getTurnover());
            row4.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row4.getCell(6).setCellValue(businessData.getNewUsers());

            //获取第五行
            XSSFRow row5 = sheet.getRow(4);
            row5.getCell(2).setCellValue(businessData.getValidOrderCount());
            row5.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for(int i=0;i<30;i++){
                LocalDate date = beginTime.plusDays(i);

                //查询某一天数据
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                XSSFRow row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());

            }

            //通过输出流将excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
